package com.sdy.auth.client.filter;

import com.sdy.auth.api.AuthApi;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.config.SsoConfig;
import com.sdy.common.model.Response;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.config.SdyMvcConfig;
import com.sdy.mvc.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SsoAuthorizationFilter extends AbstractAuthFilter {
    @Value("${res.app.code}")
    private String appCode;
    @Value("${res.app.noAuthorization:/static,/favicon.ico,/opt/file}")
    private String noAuthorization;
    @Autowired
    private AuthApi authApi;
    @Autowired
    private SsoConfig ssoConfig;
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String currentUrl = request.getRequestURI();
        // 过滤静态资源
        if (super.ignoreResource(servletRequest, noAuthorization)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 校验权限
        if (ssoConfig.getAuthorization()) {
            UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
            Integer userId = userInfo == null ? null : userInfo.getUserId();
            Response resp = authApi.checkAuthorization(userId, currentUrl, appCode);
            if (!resp.getSuccess()) {
                return;
            }
            if (!Boolean.TRUE.equals(resp.getData())) {
                String errMsg = (StringUtil.isBlank(resp.getMessage()) || "ok".equals(resp.getMessage())) ? "用户无操作权限" : resp.getMessage();
                String reqType = request.getHeader("req_type");
                if (StringUtil.equals(reqType, "async")) {
                    String respJson = JsonUtil.toJson(Response.error(errMsg, Response.Code.noAuthorization));
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(respJson == null ? "" : respJson);
                    response.getWriter().flush();
                    response.getWriter().close();
                } else {
                    response.sendRedirect(ssoConfig.getClientDomain().concat("/noaccess"));
                }
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
